package com.xinyan.controller;

import com.xinyan.vo.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {
    @Value("${ad.upload}")
    private String uploadPath;

    @GetMapping("/getFile")
    public void  getFile(HttpServletResponse response, @RequestParam(defaultValue = "true") boolean isOnline,String path){
        File file = new File(path);
        String name = file.getName();
//        System.out.println("isOnline = " + isOnline);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(file.length()));
            response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_JPEG_VALUE);
            if (isOnline){
                // 在线打开方式 文件名应该编码成UTF-8
//                System.out.println("inline方式下载");
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + URLEncoder.encode(name, "utf-8"));
            }else {
                // 纯下载方式 文件名应该编码成UTF-8
//                System.out.println("纯下载方式");
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(name, "utf-8"));
            }
            StreamUtils.copy(new BufferedInputStream(new FileInputStream(file)), outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @PostMapping("/upload")
    public R upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String name = file.getName();
        String newName = UUID.randomUUID().toString().replaceAll("-","") + originalFilename.substring(originalFilename.indexOf('.'));

        System.out.println("originalFilename = " + originalFilename);
        System.out.println("name = " + name);
        System.out.println("newName = " + newName);
        BufferedInputStream bufferedInputStream = new BufferedInputStream(file.getInputStream());
        String pathname = uploadPath + newName;
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(pathname));
        FileCopyUtils.copy(bufferedInputStream,bufferedOutputStream);
        return R.ok(pathname);
    }
}
